module Mongoid
  module Document
    def self.included(base)
      base.instance_eval { @desc_options = {} }
    end

    module ClassMethods
      # TODO mongoid last return first
      def last
        order(_id: -1).limit(1)[0]
      end

      def desc(field, description)
        # TODO 检查不存在的属性
        @desc_options[field.to_s] = description
      end

      def def_field(name, options)
        description = options.delete(:desc)
        field name, options
        desc name, description if description
      end
    end

    def serializable_hash(options={})
      hash = super
      id = hash.delete('_id')
      hash = { 'id' => id.to_s }.merge(hash)
      relations.each do |_, metadata|
        if hash.include?(metadata.key)
          id = hash.delete(metadata.key.to_s)
          hash[metadata.name.to_s] = { 'id' => id.to_s } unless hash.include?(metadata.name.to_s)
        end
      end
      hash
    end
  end
end
